<template>
  <div class="knowledge-manage">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>知识库管理</span>
              <div>
                <el-button type="primary" @click="dialogVisible = true">添加知识</el-button>
                <el-button @click="$router.push('/')">返回首页</el-button>
              </div>
            </div>
          </template>
          
          <el-table 
            :data="knowledgeBase" 
            style="width: 100%" 
            v-loading="loading"
            border
          >
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="text" label="知识内容"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加知识对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加知识"
      width="50%"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="知识内容">
          <el-input 
            v-model="form.text" 
            type="textarea" 
            :rows="4"
            placeholder="请输入常识知识内容..."
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addKnowledge" :loading="loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'KnowledgeManage',
  setup() {
    const store = useStore()
    const dialogVisible = ref(false)
    const form = ref({
      text: ''
    })
    
    // 从store获取状态
    const loading = computed(() => store.state.loading)
    const knowledgeBase = computed(() => store.state.knowledgeBase)
    const error = computed(() => store.state.error)
    
    // 加载知识库
    onMounted(() => {
      store.dispatch('fetchKnowledgeBase')
    })
    
    // 添加知识
    const addKnowledge = () => {
      if (!form.value.text.trim()) {
        ElMessage.warning('知识内容不能为空')
        return
      }
      
      store.dispatch('addKnowledge', form.value.text).then(() => {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        form.value.text = ''
      }).catch(() => {
        ElMessage.error('添加失败')
      })
    }
    
    return {
      dialogVisible,
      form,
      loading,
      knowledgeBase,
      error,
      addKnowledge
    }
  }
}
</script>

<style scoped>
.knowledge-manage {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 